<template>
    <div class="upload-box">
        <el-upload
            ref="upload"
            class="upload"
            :class="{ 'hide-close': !show }"
            :action="action"
            :headers="headers"
            :before-upload="handleBeforeUpload"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :file-list="fileList"
            :on-preview="handleDownload"
            multiple
        >
            <el-button v-if="show" slot="trigger" type="text" size="small" icon="el-icon-receiving">选择文件</el-button>
            <!-- <el-button v-if="show" :disabled="disabled" style="margin-left: 16px;" type="text" icon="el-icon-upload2" @click="submitUpload">开始上传</el-button> -->
        </el-upload>
        <TitleTips class="spe-title" title="附件资料" />
    </div>
</template>

<script>
import { UploadOption, ResponseCode } from '@/config/constants'
import { getToken } from '@/utils/auth'
import { MaintenanceProjectModel } from '@/models'
import { fileTokenKey } from '@/config/settings'
export default {
    name: 'FileUpload',
    props: {
        list: {
            type: Array,
            default: () => []
        },
        show: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            model: new MaintenanceProjectModel(),
            action: UploadOption.ACTION,
            headers: {
                [fileTokenKey]: getToken()
            },
            fileList: [],
            files: []
        }
    },
    watch: {
        files: {
            handler(newval) {
                const disabled = newval.some((item) => item.status && item.status !== 'success')
                this.$emit('load', disabled)
            },
            deep: true
        },
        // 监听回传的文件列表
        list: {
            handler(newval) {
                this.fileList = newval
                this.files = this.fileList
            },
            deep: true
        }
    },
    methods: {
        handleDownload(file) {
            const url = file.url || file.response.data.objectUrl
            const a = document.createElement('a')
            a.href = url
            a.download = file.name
            document.body.appendChild(a)
            a.click()
            // 把a标签删除，减少dom节点冗余
            document.body.removeChild(a)
        },
        handleBeforeUpload(file) {
            // 如果files里有相同name文件，说明已经上传过同名文件
            const length = this.files.filter((item) => item.name === file.name).length
            if (length >= 2) {
                this.$message.error(`已经上传相同名称文件${file.name}`)
                return false
            }

            // 文件大于100MB的禁止上传
            if (file.size / 1024 / 1024 > 100) {
                this.$message.error(`文件${file.name}大小超过100MB`)
                return false
            }
            return true
        },
        handleChange(file, fileList) {
            this.files = fileList
        },
        handleRemove(file) {
            this.files.some((item, index) => {
                if (item.uid === file.uid) {
                    this.files.splice(index, 1)
                    return true
                }
            })
        },
        handleSuccess(response, file, fileList) {
            if (response.code === ResponseCode.success) {
                this.files = fileList
            } else {
                fileList.some((item, index) => {
                    if (item.uid === file.uid) {
                        fileList.splice(index, 1)
                        return true
                    }
                })
                this.$message.error('文件上传失败，请重试！')
            }
        },
        handleError() {
            this.$message.error('网络异常，请稍后再试!')
        },
        getFileList() {
            const annexList = this.files.map((item) => {
                return {
                    name: item.name,
                    url: item.url || item.response.data.objectUrl
                }
            })
            return annexList
        }
        // submitUpload() {
        //     this.disabled = true
        //     const annexList = this.files.map(item => {
        //         return {
        //             name: item.name,
        //             url: item.url || item.response.data.objectUrl
        //         }
        //     })
        //     const data = {
        //         id: this.id,
        //         annexList
        //     }
        //     this.model.saveOrUpdate(data).then(() => {
        //         this.$message.success('上传成功！')
        //     }).finally(() => {
        //         this.disabled = false
        //     })
        // },
    }
}
</script>

<style lang="scss" scoped>
.upload-box {
    position: relative;
    width: 700px;
    margin-top: 24px;
    .upload {
        margin-left: 80px;
        position: relative;
        z-index: 20;
        ::v-deep {
            .el-upload-list {
                margin-left: -85px;
                margin-bottom: 24px;
            }
        }
    }
    .spe-title {
        position: absolute;
        top: 5px;
        z-index: 10;
    }
    .hide-close {
        ::v-deep .el-icon-close {
            display: none;
        }
    }
}
</style>
